package com.geega.geetest.aopLog;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class PrintLogAspect{
    private Gson gson = new Gson();

    @Around(value = "@annotation(com.geega.geetest.aopLog.PrintLog)")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String printLogValue = method.getDeclaredAnnotation(PrintLog.class).value();

        long startTime = System.currentTimeMillis();
        log.info("{}:{}.{}-Request:[{}]",printLogValue,method.getDeclaringClass().getSimpleName(),method.getName(),gson.toJson(joinPoint.getArgs()));

        Object response = joinPoint.proceed(); //执行目标方法

        log.info("{}:{}.{}-Response:[{}], Spend-times : [{}ms]",printLogValue,method.getDeclaringClass().getSimpleName(),method.getName(),gson.toJson(response),System.currentTimeMillis() - startTime);

        return response;
    }
}
